package google.architecture.coremodel.viewmodel;

import android.app.Application;
import android.support.annotation.NonNull;

import google.architecture.coremodel.constant.ErrorCode;
import google.architecture.coremodel.datamodel.http.entities.ProductData;
import google.architecture.coremodel.datamodel.http.entities.ShoppingCarItem;
import google.architecture.coremodel.exception.LackOfStockException;
import google.architecture.coremodel.navigator.PayAndShopCarNavigator;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 保存生命周期和UI所使用的数据
 * Created by dxx on 2017/11/10.
 */

public class PayAndAddShopCarModel extends PaymentViewModel {
    public PayAndAddShopCarModel(@NonNull Application application) {
        super(application);
    }
    public void add2ShoppingCar(ProductData.Product product){
        this.add2ShoppingCar(product,1);
    }
    public void add2ShoppingCar(ProductData.Product product,int count){
        mAutoVenderDataRepository.add2ShoppingCar(product,count)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ShoppingCarItem>() {
                    @Override
                    public void accept(ShoppingCarItem s) {
                        mAppConfigHelper.saveHasData(true);
                        mNavigator.onAddShopCar(s);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        if(throwable instanceof LackOfStockException){
                            Exception exception=(Exception)throwable;
                            mNavigator.showError(ErrorCode.LACK_OF_STOCK,exception.getMessage());
                        }
                    }
                });
    }
    protected PayAndShopCarNavigator mNavigator;


    public void setNavigator(PayAndShopCarNavigator navigator) {
        super.setNavigator(navigator);
        mNavigator = navigator;
    }
}
